package ExamplePackage;


import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class ConnectionManager {

	private static ConnectionManager uniqueInstance = null;

	private Connection con = null;
	private final String driver = "org.apache.derby.jdbc.EmbeddedDriver";

	private String dbname = "jdbc:derby:D:/MijnDocumenten/school/WebTech1/Nathalie/myDB;create=true";


	public ConnectionManager() {
		//this.dbname = dbname;
		if (!dbExists(dbname)) {
			System.err.println("de database bestaat niet....");
		}
		Statement stmt;
		try {
 		stmt = con.createStatement();
			
 		ResultSet rs;
			 rs = stmt.executeQuery("Select * From users");

			rs.close();
		} catch (SQLException e) {
			System.out.println("connectionmanager : 34");
			e.printStackTrace();
			try {			
				System.out.println("ConnectionManager : 37");
				stmt = con.createStatement();
				System.out.println("ConnectionManager : 39");
				stmt.executeUpdate("CREATE table users (FirstName varchar(255), LastName varchar(255), username varchar(255), password varchar(255) )");
					System.out.println("table created");
				stmt.close();
				con.close();
			} catch (SQLException e1) {
				System.out.println("e1");
				e1.printStackTrace();
			}
		}
	}
	
//	public static void main(String args[]){
//		DatabaseManager db = getInstance("jdbc:derby:D:/MijnDocumenten/school/WebTech/DB");
//		AuctionDAO test = new AuctionDAO(db);
//		CatagoryDAO test1 = new CatagoryDAO(db);
//		PersonDAO test2 = new PersonDAO(db);
//		System.out.println("testing");
//		test2.insertPerson("Henk2", "Thuis", "Vijf", "Thuis@vijf.nl", "Henk5", "5vijf");
//		test1.insertCatagory("muziek2");
//		test.insertAuction("test2", "1", 12.0, new Date(2011, 12, 12), 1, "muziek2");
//		
//		for(Auction a : test.getFirstFewAuctions() ){
//			
//			System.out.println(a.toString());
//		}
//	}

	public static synchronized ConnectionManager getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new ConnectionManager();	
		}
		return uniqueInstance;
	}

	private boolean dbExists(String dataSource) {
		boolean exists = false;
		try {
			Class.forName(driver);
			con = DriverManager.getConnection(dbname);

			exists = true;
		} catch (Exception e) {
			System.out.println("Henk");
			e.printStackTrace(); // Do nothing, as DB does not (yet) exist
		}
		return (exists);
	}

	public void close() {
		try {
			con = DriverManager.getConnection(dbname + ";shutdown=true");
		} catch (SQLException se) {
			; // Do Nothing. System has shut down.
			con = null;
		}
	}

	public Connection getConnection() {
		return con;
	}
}
